import { useEffect, useState } from "react";
import { RespSysDataType, getDictData, getUserDependParams, getDeptTree, getAllowUserUseRoles } from "@/components/app/sys/api";

interface TreeSelectData {
  title: string;
  value: number;
  // extFiled?: string;
  children?: TreeSelectData[];
}

interface InitData {
  sexList: { label: string; value: string; }[];
  sysPostList: { label: string; value: number; }[];
  sysRoleList: { label: string; value: number; }[];
  orgTreeSelectData: TreeSelectData[];
  allowUserUseAdminRoleList: RespSysDataType.AllowUserUseAdminRoleItem[];
}

export const useCreateUser = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [initData, setInitData] = useState<InitData>({ sexList: [], sysPostList: [], sysRoleList: [], orgTreeSelectData: [], allowUserUseAdminRoleList: [] });

  useEffect(() => {
    setLoading(true);
    Promise.all([getDictData({ dictType: "sys_user_sex" }), getUserDependParams(), getDeptTree(), getAllowUserUseRoles()]).then((resp) => {
      const [sexResp, userDependParamsResp, deptTreeResp, allowUserUseRoleResp] = resp;
      const { roleList, posts } = userDependParamsResp.data;
      setInitData({
        sexList: (sexResp.data.values || []).map(item => ({ label: item.value, value: item.key })),
        sysRoleList: (roleList || []).map(item => ({ label: item.name, value: item.id })),
        sysPostList: (posts || []).map(item => ({ label: item.postName, value: item.postId })),
        orgTreeSelectData: formatDeptTree(deptTreeResp.data.deps),
        allowUserUseAdminRoleList: allowUserUseRoleResp.data || [],
      })
      setLoading(false);
    });
  }, []);

  return { loading, initData }
}

/**
 * 格式化组织树
 */
const formatDeptTree = (data: RespSysDataType.DeptTreeItem[]): TreeSelectData[] => {
  return data.map(item => {
    return ({
      value: item.deptId,
      title: item.deptName,
      children: item.children ? formatDeptTree(item.children) : []
    })
  })
}
